package us.wili.dev.client.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import us.wili.dev.client.model.WechatTemplate;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class Wxapi {


    public static final String APP_ID = "wx3302803d55ae4f79";
    public static final String appSecrct= "f8173c416fa6c0d800cf824db52779b8";


    private final static LoadingCache<String, String> mAccessTokenCache =
            CacheBuilder.newBuilder()
                    .expireAfterWrite(7200, TimeUnit.SECONDS)
                    .build(new CacheLoader<String, String>() {
                        @Override
                        public String load(String key) {
                            // key: appId#appSecret
                            String[] array = key.split("#");
                            if (null == array || array.length != 2) {
                                throw new IllegalArgumentException("load access_token error, key = " + key);
                            }
                            return getAccessToken(array[0], array[1]);
                        }
                    });

    public static String getAccessToken() {
        WeixinPayConfig config = new WeixinPayConfig();
        String cacheKey = APP_ID + "#" + appSecrct;
        try {
            return mAccessTokenCache.get(cacheKey);
        } catch (ExecutionException e) {
        }
        return null;
    }

    private static String getAccessToken(String appId, String appSecret) {
        String apiUrl = StrUtil.format(//
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}",//
                appId, appSecret
        );
        String body = HttpRequest.get(apiUrl).execute().body();
        return throwErrorMessageIfExists(body).getString("access_token");
    }

    public static void templateSend(String accessToken, WechatTemplate template) {
        String apiUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="//
                + (StringUtils.isEmpty(accessToken) ? getAccessToken() : accessToken);
        Gson gson = new Gson();
        String json = gson.toJson(template);
        String body = HttpRequest.post(apiUrl).body(json).execute().body();
        System.out.printf(body);
        throwErrorMessageIfExists(body);
    }



    private static JSONObject throwErrorMessageIfExists(String body) {
        String callMethodName = (new Throwable()).getStackTrace()[1].getMethodName();
        JSONObject jsonObject = JSON.parseObject(body);
        if (jsonObject.containsKey("errcode") && jsonObject.getIntValue("errcode") > 0) {
            throw new RuntimeException(String.format("#WechatApi[{}] call error: {}", callMethodName, body));
        }
        return jsonObject;
    }
}
